package com.android.test.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;


public class DateUtil {
    private static final String TAG = "DateUtil";

    private static final DateFormat DF_DATETIME = new SimpleDateFormat(
	    "yyyy-MM-dd'T'HH:mm:ss.SSS");
    private static final DateFormat DF_DATE = new SimpleDateFormat(
	    "yyyy-MM-dd-ww");
    private static final DateFormat DF_LOCALE = DateFormat
	    .getDateTimeInstance();
    private static final DateFormat DF_DATE_LOCALE = DateFormat
	    .getDateInstance();

    public static String getDateTime(Calendar date) {
	return DF_DATETIME.format(date.getTime());
    }

    public static String getDate(Calendar date) {
	return DF_DATE.format(date.getTime());
    }

    public static String getLocaleDateTime(Calendar date) {
	return DF_LOCALE.format(date.getTime());
    }

    public static String getLocaleDate(Calendar date) {
	return DF_DATE_LOCALE.format(date.getTime());
    }

    public static Calendar parseDateTime(String date) {
	Calendar c = Calendar.getInstance(Locale.ENGLISH);
	try {
	    c.setTime(DF_DATE.parse(date));
	} catch (ParseException e) {
	}
	return c;
    }

    public static Calendar parseDate(String date) {
	Calendar c = Calendar.getInstance(Locale.ENGLISH);
	try {
	    c.setTime(DF_DATE.parse(date));
	} catch (ParseException e) {

	}
	return c;
    }

    public static int diffDays(Calendar g1, Calendar g2) {

	int elapsed = 0;
	Calendar gc1, gc2;

	if (g2.after(g1)) {
	    gc2 = (Calendar) g2.clone();
	    gc1 = (Calendar) g1.clone();
	} else {
	    gc2 = (Calendar) g1.clone();
	    gc1 = (Calendar) g2.clone();
	}

	gc1.clear(Calendar.MILLISECOND);
	gc1.clear(Calendar.SECOND);
	gc1.clear(Calendar.MINUTE);
	gc1.clear(Calendar.HOUR_OF_DAY);

	gc2.clear(Calendar.MILLISECOND);
	gc2.clear(Calendar.SECOND);
	gc2.clear(Calendar.MINUTE);
	gc2.clear(Calendar.HOUR_OF_DAY);

	while (gc1.before(gc2)) {
	    gc1.add(Calendar.DATE, 1);
	    elapsed++;
	}
	return elapsed;
    }

    public static int diffMonths(Calendar g1, Calendar g2) {

	int elapsed = 0;
	Calendar gc1, gc2;

	if (g2.after(g1)) {
	    gc2 = (Calendar) g2.clone();
	    gc1 = (Calendar) g1.clone();
	} else {
	    gc2 = (Calendar) g1.clone();
	    gc1 = (Calendar) g2.clone();
	}

	gc1.clear(Calendar.MILLISECOND);
	gc1.clear(Calendar.SECOND);
	gc1.clear(Calendar.MINUTE);
	gc1.clear(Calendar.HOUR_OF_DAY);
	gc1.clear(Calendar.DATE);

	gc2.clear(Calendar.MILLISECOND);
	gc2.clear(Calendar.SECOND);
	gc2.clear(Calendar.MINUTE);
	gc2.clear(Calendar.HOUR_OF_DAY);
	gc1.clear(Calendar.DATE);

	while (gc1.before(gc2)) {
	    gc1.add(Calendar.MONTH, 1);
	    elapsed++;
	}
	return elapsed;
    }
}